/**
 * 	 @author Morozan Ion 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dddforandroid.api;

import java.lang.reflect.Field;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

public class TypeContentProvider extends ContentProvider {

	// TODO: add to the manifest:
	// <provider
	// android:authorities="com.dddforandroid.database"
	// android:multiprocess="true"
	// android:name=".providers.ExampleContentProvider"/>

	public static String AUTHORITY = "com.dddforandroid.api.TypeContentProvider";

	private static UriMatcher sUriMatcher;

	private static int DATABASE_VERSION = 1;
	private static String DATABASE_NAME = "note.db";
	private static String TABLE_NAME = "note";

	public static final int KIND = 1;
	public static final int TABLE = 2;

	private static String BASE_PATH = "note";
	public static Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/"
			+ BASE_PATH);

	public static String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
			+ "/" + BASE_PATH;
	public static String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
			+ "/" + BASE_PATH;
	public static String ID = "id";

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			String createTable = null;
			Field[] fields = SQLiteBackup.Kind.getDeclaredFields();
			int fieldsNo = fields.length;

			createTable = "CREATE TABLE " + TABLE_NAME + " (";
			createTable += "id VARCHAR PRIMARY KEY,";
			
			for (Field field : fields) {
				fieldsNo--;
				createTable += field.getName() + " VARCHAR";
				if (fieldsNo != 0)
					createTable += ",";
			}

			createTable += ")";

			db.execSQL(createTable);
			createTable = null;
		}

		/*
		 * Upgrading database from version oldVersion to newVersion, which will
		 * destroy all old data
		 */
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}

	private DatabaseHelper dbHelper;

	/*
	 * Delete item or all table How to use: Uri uri =
	 * Uri.parse(ExampleContentProvider.CONTENT_URI + "/4");
	 * getContentResolver().delete(uri, null, null);
	 */
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		int count;
		switch (sUriMatcher.match(uri)) {
		case KIND:
			count = db.delete(TABLE_NAME, "id = " + uri.getLastPathSegment(),
					whereArgs);
			break;
		case TABLE:
			count = db.delete(TABLE_NAME, where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case TABLE:
			return CONTENT_TYPE;
		case KIND:
			return CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	/*
	 * Insert item to the table. How to use: ContentValues mValues = new
	 * ContentValues(); mValues.put("title", "Title");
	 * mValues.put("description", "Description");
	 * getContentResolver().insert(ExampleContentProvider, mValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// if (sUriMatcher.match(uri) != NOTE) { throw new
		// IllegalArgumentException("Unknown URI " + uri); }

		ContentValues values;
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}

		SQLiteDatabase db = dbHelper.getWritableDatabase();

		long rowId = db.insert(TABLE_NAME, null, values);

		if (rowId > 0) {
			Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(noteUri, null);
			return noteUri;
		}

		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {

		dbHelper = new DatabaseHelper(getContext());
		return true;
	}

	/*
	 * Query How to use: String[] projection = {"title", "description" }; Cursor
	 * cursor = getContentResolver().query(ExampleContentProvider.CONTENT_URI,
	 * projection, null, null, null);
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(TABLE_NAME);

		switch (sUriMatcher.match(uri)) {

		case KIND:
			qb.appendWhere("id=" + uri.getLastPathSegment());
			break;

		case TABLE:
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri + " suri "
					+ sUriMatcher.toString());
		}

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);

		return c;

	}

	/*
	 * Update item in the table How to use: Uri uri =
	 * Uri.parse(ExampleContentProvider.CONTENT_URI + "/4"); ContentValues
	 * mValues = new ContentValues(); mValues.put("title", "NewTitle");
	 * mValues.put("description", "NewDescription");
	 * getContentResolver().update(uri, mValues, null, null);
	 */
	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {

		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
		case KIND:
			count = db.update(TABLE_NAME, values,
					"id =" + uri.getLastPathSegment(), whereArgs);
			break;
		case TABLE:
			count = db.update(TABLE_NAME, values, where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", KIND);
		sUriMatcher.addURI(AUTHORITY, BASE_PATH, TABLE);

	}

}